<?php

require_once 'include/config.php';
require_once 'include/http.php';
require_once 'wechat.php';
$upload = new upload();

class upload{
    
    
    private $appid = '';
    private $appsecret = '';
    private $http = '';
    
    public function __construct() {
        $this->appid = constant('APPID');
        $this->appsecret = constant('APPSECRET');
        $this->http = new http();
        //获取access_token
        $wechat = new wechat();
        $access_token = $wechat->getAccessToken();
        //接口业务
        $type = isset($_GET['type'])?$_GET['type']:'';
        $ret = '';
        switch ($type) {
            case 'upload_file':
                //上传文件到本地
                $filename = $this->uploadFile();
                //新增素材
                $ret = $this->createFile($access_token,$filename);
                //保存数据库
                
                break;
            
        }
        echo $ret;
    }
    //新增素材
    private function createFile($access_token,$filename) {
        if($_POST['state'] == 1){
            $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=image";
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image";
        }
        $json = $this->http->http_request($url,[],$filename);
        return  $json;
    }
    //上传文件到本地
    private function uploadFile() {
        //获取文件
        $file = $_FILES['file'];
//        print_r($file);exit;
        //得到文件拓展名
        $ext = pathinfo($file['name'],PATHINFO_EXTENSION);
        //上传文件名
        $name = time().".".$ext;
        //上传路径
        $path = __DIR__."/upload/";
        //文件上传
        move_uploaded_file($file['tmp_name'], $path.$name);
        return $path.$name;
    }
    
    
}

